<?php
class Modules{
	private static $instance = NULL;
	private $activeModules = array();
	private $deactivatedModules = array();
	
	public static function getInstance() {
		if(self::$instance == NULL) self::$instance = new Modules();
		return self::$instance;
	}
	
	private function __construct() {}
	private function __clone() {}
	
	public function addModule($moduleName,$module) {
		$this->activeModules[$moduleName] = $module;
	}
	
	public function addAlldModules($id,$moduleName) {
		$this->deactivatedModules[$id] = $moduleName;
	}
	
	public function isInstalled($moduleName) {
		if(in_array($moduleName,$this->deactivatedModules)) {
			return array_search($moduleName,$this->deactivatedModules);
		}
		return false;
	}
	
	public function getModule($moduleName) {
		return $this->activeModules[$moduleName];
	}
	
	public function getAllActivatedModules() {
		return $this->activeModules;
	}
	
	public function loadModules() {
		$query = DB::getInstance()->query("
			SELECT
				id,
				moduleName,
				moduleFolder,
				moduleClass,
				moduleEnabled
			FROM
				".Tables::$moduleTbl."");
		while($mod = DB::fetchArray($query)) {
			if($mod['moduleEnabled'] == 0) {
				include("modules/".$mod['moduleFolder']."/".$mod['moduleClass'].".php");
				$modInstance = new $mod['moduleClass'];
				
				Modules::getInstance()->addModule($mod['moduleName'],$modInstance);
			}
			Modules::getInstance()->addAlldModules($mod['id'],$mod['moduleName']);
		}
		
		$allModules = Modules::getInstance()->getAllActivatedModules();
		foreach($allModules as $modName => $inst) {
			$inst->initModule();
				
			// ADD Allowed Sites
			if(is_array($inst->getAllowedSites())) Tables::$allowedSites = array_merge(Tables::$allowedSites,$inst->getAllowedSites());
			if(is_array($inst->getRedirectUrl())) Tables::$redirectUrl = array_merge(Tables::$redirectUrl,$inst->getRedirectUrl());
				
			if(is_array($inst->getHtaccessData())) Navigation::$htaccess = array_merge(Navigation::$htaccess,$inst->getHtaccessData());
			if(is_array($inst->getNaviTemplates())) Navigation::$naviTemplates = array_merge(Navigation::$naviTemplates,$inst->getNaviTemplates());
				
			if(Admin::isLoggedIn()) AdminNavigation::$moduleLinks[$modName] = $inst->getAdminModuleLinks();
		}
	}
	
	public function installModule($moduleFolder) {
		if(!file_exists("./modules/".$moduleFolder."/module.xml")) exit;
		
		$xmlData = simplexml_load_file("./modules/".$moduleFolder."/module.xml");
		
		include("modules/".$moduleFolder."/".$xmlData->class.".php");
		$className = (String)$xmlData->class;
		$modInstance = new $className;
		
		$modInstance->install();
		
		// Add Entry
		DB::getInstance()->query("
			INSERT INTO
				".Tables::$moduleTbl."
			SET
				moduleName = '".DB::parseVar((String)$xmlData->name)."',
				moduleFolder = '".$moduleFolder."',
				moduleDescription = '".DB::parseVar((String)$xmlData->description)."',
				moduleClass = '".DB::parseVar((String)$xmlData->class)."',
				moduleAuthor = '".DB::parseVar((String)$xmlData->author)."',
				moduleAuthorURL = '".DB::parseVar((String)$xmlData->authorUrl)."',
				moduleVersion = '".DB::parseVar((String)$xmlData->version)."',
				moduleEnabled = '1',
				moduleInstallDate = '".time()."'");
	}
	
	
	public function deinstallModule($id,$name) {
		if(!is_numeric($id)) exit;
		
		$instance = Modules::getModule($name);
		$instance->deinstall();
		
		DB::getInstance()->query("
			DELETE FROM
				".Tables::$moduleTbl."
			WHERE
				id = '".$id."'");
	}
	
	public function getAllModules() {
		$modules = array();
		$query = DB::getInstance()->query("
			SELECT
				id,
				moduleName,
				moduleFolder,
				moduleDescription,
				moduleAuthor,
				moduleAuthorURL,
				moduleInstallDate,
				moduleVersion,
				moduleClass,
				moduleEnabled
			FROM
				".Tables::$moduleTbl."");
		while($mod = DB::fetchArray($query)) {
			$modules[] = $mod;
		}
		return $modules;
	}
	
	public function updateEnabled($id,$enabled) {
		if(!is_numeric($id) || !is_numeric($enabled)) exit;
		
		DB::getInstance()->query("
			UPDATE
				".Tables::$moduleTbl."
			SET
				moduleEnabled = '".$enabled."'
			WHERE
				id = '".$id."'");
	}
	
	public function downloadModule($folder) {
		if(!General::urlExists("http://ld-network.de/moduleExternTest/".$folder."/module.xml")) exit;
		if(file_exists("./modules/".$folder)) exit;
		
		$module = simplexml_load_file('http://ld-network.de/moduleExternTest/'.$folder.'/module.xml');
		
		// Create Module-Folder
		mkdir("./modules/".$folder,0777);
		
		foreach ($module->Folders->folder as $folders) {
			mkdir("./modules/".$folder."/".$folders,0777);
		}
		
		foreach ($module->Files->file as $files) {
    		// Dateien kopieren
    		$content = file_get_contents("http://ld-network.de/moduleExternTest/".$folder."/".$files);
    		$finfo = pathinfo($files);

    		if($finfo['dirname'] != ".") {
    			$dirs = explode("/",$finfo['dirname']);
    			
    			if(count($dirs) == 1) {
					// Create Folders
    				if(!file_exists("./modules/".$folder."/".$dirs[0])) 
    					mkdir("./modules/".$folder."/".$dirs[0],0777);
    			}else{
    				foreach($dirs as $key => $dirsname) {
    					// Path
    					$path = "";
    					if($key != 0) {
    						for($i=0;$i<$key;$i++) {
    							$path .= $dirs[$i]."/";
    						}
    					}
    					$path .= $dirsname."/";
    					if(!file_exists("./modules/".$folder."/".$path)) {
    						//echo $path."\n";
    						mkdir("./modules/".$folder."/".$path,0777);
    					}
    				}
    			}
    			//mkdir("../modules/".$dirname."/".$finfo['dirname'],0777);
    		}
    		$fres = fopen("./modules/".$folder."/".$files,"w+");
    		fwrite($fres,$content);
    		fclose($fres);
    	}
	}
}
?>